<script setup>
import { ref, computed, onMounted } from 'vue'
import { processPayment, formatPrice } from '../utils/paymentUtils.js'
import { useRouter } from 'vue-router'

// Props
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  product: {
    type: Object,
    default: () => ({
      id: '',
      name: '',
      price: 0,
      details: {}
    })
  },
  userLevel: {
    type: String,
    default: '游客'
  },
  isLoggedIn: {
    type: Boolean,
    default: false
  },
  userInfo: {
    type: Object,
    default: null
  }
})

// Emits
const emit = defineEmits(['close', 'payment-success'])

const router = useRouter()

// 支付状态
const paymentStatus = ref('idle') // idle, processing, success, error
const errorMessage = ref('')
const successMessage = ref('')

// 支付方式
const paymentMethod = ref('wechat') // wechat, alipay, card, points

// 优惠券
const hasCoupon = ref(false)
const couponCode = ref('')
const validCoupon = ref(false)

// 支付表单数据
const paymentForm = ref({
  name: '',
  phone: '',
  email: '',
  agreeTerms: false
})

// 可用积分
const availablePoints = ref(0)
const usePoints = ref(false)
const pointsToUse = ref(0)

// 促销代码和折扣
const promoCodes = [
  { code: 'SHADOW10', discount: 0.1, description: '全场九折优惠' },
  { code: 'NEWUSER99', discount: 20, description: '新用户首月优惠' },
  { code: 'VIP66', discount: 0.15, description: '会员专享85折' }
]

// 会员等级折扣
const memberDiscounts = {
  '学子会员': 0.95,
  '传人会员': 0.9,
  '大师会员': 0.85
}

// 计算优惠券折扣金额
const couponDiscount = computed(() => {
  // 根据不同产品类型提供不同的优惠券折扣
  switch (props.product?.type) {
    case 'membership':
      return 10 // 会员优惠10元
    case 'single_play':
      return 5 // 单个剧目优惠5元
    case 'ticket':
      return 3 // 演出票优惠3元
    case 'package':
      return 20 // 套餐优惠20元
    default:
      return 5
  }
})

// 计算实际支付金额
const finalPrice = computed(() => {
  let price = props.product.price
  
  // 应用会员等级折扣
  if (props.userLevel && memberDiscounts[props.userLevel]) {
    price *= memberDiscounts[props.userLevel]
    console.log(`应用${props.userLevel}折扣: ${memberDiscounts[props.userLevel]}`)
  }
  
  // 应用优惠券折扣
  if (validCoupon.value) {
    price = Math.max(0, price - couponDiscount.value)
  }
  
  // 应用积分抵扣
  if (usePoints.value && pointsToUse.value > 0) {
    // 100积分 = 1元
    const pointDiscount = pointsToUse.value / 100
    price = Math.max(0, price - pointDiscount)
    console.log(`应用积分抵扣: ${pointDiscount}`)
  }
  
  return Math.round(price * 100) / 100
})

// 计算节省金额
const savings = computed(() => {
  return Math.round((props.product.price - finalPrice.value) * 100) / 100
})

// 验证优惠券
const validateCoupon = () => {
  if (!couponCode.value) {
    validCoupon.value = false
    return
  }
  
  const promo = promoCodes.find(p => p.code === couponCode.value.toUpperCase())
  validCoupon.value = !!promo
  
  if (promo) {
    successMessage.value = `优惠券验证成功: ${promo.description}`
    setTimeout(() => {
      successMessage.value = ''
    }, 3000)
  } else {
    errorMessage.value = '无效的优惠券代码'
    setTimeout(() => {
      errorMessage.value = ''
    }, 3000)
  }
}

// 处理积分使用
const handlePointsChange = () => {
  if (!usePoints.value) {
    pointsToUse.value = 0
    return
  }
  
  // 最大可使用积分 = 价格 * 100
  const maxPoints = Math.floor(props.product.price * 100)
  pointsToUse.value = Math.min(availablePoints.value, maxPoints)
}

// 执行支付
const handlePayment = async () => {
  // 表单验证
  if (!paymentForm.value.agreeTerms) {
    errorMessage.value = '请阅读并同意服务条款'
    setTimeout(() => {
      errorMessage.value = ''
    }, 3000)
    return
  }
  
  if (!paymentForm.value.name || !paymentForm.value.phone) {
    errorMessage.value = '请填写必要的联系信息'
    setTimeout(() => {
      errorMessage.value = ''
    }, 3000)
    return
  }
  
  // 开始支付处理
  paymentStatus.value = 'processing'
  
  try {
    // 使用支付工具函数处理支付
    const paymentResult = await processPayment({
      amount: finalPrice.value,
      method: paymentMethod.value,
      productId: props.product?.id,
      usePoints: usePoints.value && pointsToUse.value > 0,
      couponCode: couponCode.value
    })
    
    // 支付成功
    paymentStatus.value = 'success'
    successMessage.value = '支付成功！正在处理您的订单...'
    
    // 生成订单ID
    const orderId = 'ORD' + Date.now().toString().substring(4)
    
    // 模拟订单处理延迟
    setTimeout(() => {
      // 构建支付结果
      const resultData = {
        orderId: orderId,
        product: {
          ...props.product,
          type: 'ticket' // 确保产品类型为ticket
        },
        amount: finalPrice.value,
        paymentMethod: paymentMethod.value,
        timestamp: new Date().toISOString(),
        userInfo: paymentForm.value,
        discountInfo: {
          memberLevel: props.userLevel,
          coupon: validCoupon.value ? couponCode.value : null,
          usedPoints: usePoints.value ? pointsToUse.value : 0
        }
      }
      
      console.log('支付结果:', resultData)
      
      // 触发成功事件
      emit('payment-success', resultData)
      
      // 重置状态并关闭弹窗
      resetPaymentState()
      emit('close')
    }, 2000)
  } catch (error) {
    // 支付失败处理
    paymentStatus.value = 'error'
    errorMessage.value = '支付处理失败，请稍后再试'
    setTimeout(() => {
      errorMessage.value = ''
    }, 3000)
  }
}

// 重置支付状态
const resetPaymentState = () => {
  paymentStatus.value = 'idle'
  errorMessage.value = ''
  successMessage.value = ''
  hasCoupon.value = false
  couponCode.value = ''
  validCoupon.value = false
  usePoints.value = false
  pointsToUse.value = 0
  paymentForm.value.agreeTerms = false
}

// 关闭支付弹窗
const closeModal = () => {
  if (paymentStatus.value !== 'processing') {
    resetPaymentState()
    emit('close')
  }
}

// 安装时加载用户数据
onMounted(() => {
  // 从本地存储获取用户积分
  const storedUserInfo = localStorage.getItem('userInfo')
  if (storedUserInfo) {
    const userInfo = JSON.parse(storedUserInfo)
    availablePoints.value = userInfo.points || 0
    paymentForm.value.name = userInfo.username || ''
    paymentForm.value.phone = userInfo.phone || ''
    paymentForm.value.email = userInfo.email || ''
  }
})
</script>

<template>
  <!-- 支付弹窗蒙层 -->
  <div v-if="show" class="payment-modal-overlay" @click.self="closeModal">
    <div class="payment-modal">
      <!-- 弹窗头部 -->
      <div class="modal-header">
        <h3 class="modal-title">支付确认</h3>
        <button 
          class="close-button" 
          @click="closeModal"
          :disabled="paymentStatus === 'processing'"
        >
          ×
        </button>
      </div>
      
      <!-- 支付状态提示 -->
      <div v-if="errorMessage" class="alert error">
        {{ errorMessage }}
      </div>
      <div v-if="successMessage" class="alert success">
        {{ successMessage }}
      </div>
      
      <!-- 订单信息 -->
      <div class="order-summary">
        <h4>订单信息</h4>
        <div class="order-details">
          <div class="detail-item">
            <span class="detail-label">商品名称：</span>
            <span class="detail-value">{{ product.name }}</span>
          </div>
          <!-- 显示票务详情 -->
          <div v-if="product.details && typeof product.details === 'object'">
            <div class="detail-item" v-if="product.details.showTitle">
              <span class="detail-label">演出名称：</span>
              <span class="detail-value">{{ product.details.showTitle }}</span>
            </div>
            <div class="detail-item" v-if="product.details.showDate">
              <span class="detail-label">演出日期：</span>
              <span class="detail-value">{{ product.details.showDate }}</span>
            </div>
            <div class="detail-item" v-if="product.details.location">
              <span class="detail-label">演出地点：</span>
              <span class="detail-value">{{ product.details.location }}</span>
            </div>
            <div class="detail-item" v-if="product.details.ticketType">
              <span class="detail-label">票种类型：</span>
              <span class="detail-value">{{ product.details.ticketType }}</span>
            </div>
            <div class="detail-item" v-if="product.details.features && product.details.features.length > 0">
              <span class="detail-label">票种特点：</span>
              <span class="detail-value">
                <span v-for="(feature, index) in product.details.features" :key="index" class="feature-tag">{{ feature }}</span>
              </span>
            </div>
          </div>
          <!-- 会员等级显示 -->
          <div v-else-if="product.details" class="detail-item">
            <span class="detail-label">商品详情：</span>
            <span class="detail-value">{{ product.details }}</span>
          </div>
          <!-- 会员等级显示 -->
          <div class="detail-item" v-if="userLevel && userLevel !== '游客'">
            <span class="detail-label">会员等级：</span>
            <span class="detail-value user-level-badge">{{ userLevel }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">原价：</span>
            <span class="detail-value original-price">¥{{ product.price.toFixed(2) }}</span>
          </div>
          <div v-if="savings > 0" class="detail-item discount">
            <span class="detail-label">节省：</span>
            <span class="detail-value savings">-¥{{ savings.toFixed(2) }}</span>
          </div>
          <div class="detail-item total">
            <span class="detail-label">应付金额：</span>
            <span class="detail-value total-price">¥{{ finalPrice.toFixed(2) }}</span>
          </div>
        </div>
      </div>
      
      <!-- 用户信息 -->
      <div class="user-info-form">
        <h4>联系信息</h4>
        <div class="form-group">
          <label for="name">姓名</label>
          <input 
            id="name"
            v-model="paymentForm.name"
            type="text"
            placeholder="请输入姓名"
            :disabled="paymentStatus === 'processing'"
          >
        </div>
        <div class="form-row">
          <div class="form-group">
            <label for="phone">手机号</label>
            <input 
              id="phone"
              v-model="paymentForm.phone"
              type="tel"
              placeholder="请输入手机号"
              :disabled="paymentStatus === 'processing'"
            >
          </div>
          <div class="form-group">
            <label for="email">邮箱 (选填)</label>
            <input 
              id="email"
              v-model="paymentForm.email"
              type="email"
              placeholder="请输入邮箱"
              :disabled="paymentStatus === 'processing'"
            >
          </div>
        </div>
      </div>
      
      <!-- 优惠券输入 -->
      <div class="coupon-section">
        <div class="coupon-toggle">
          <input 
            id="has-coupon"
            v-model="hasCoupon"
            type="checkbox"
            :disabled="paymentStatus === 'processing'"
          >
          <label for="has-coupon">使用优惠券</label>
        </div>
        <div v-if="hasCoupon" class="coupon-input-group">
          <input 
            v-model="couponCode"
            type="text"
            placeholder="请输入优惠券代码"
            :disabled="paymentStatus === 'processing'"
          >
          <button 
            class="btn btn-outline"
            @click="validateCoupon"
            :disabled="paymentStatus === 'processing' || !couponCode"
          >
            验证
          </button>
          <span v-if="validCoupon" class="coupon-valid">✓ 已应用</span>
        </div>
      </div>
      
      <!-- 积分抵扣 -->
      <div v-if="availablePoints > 0" class="points-section">
        <div class="points-info">
          <div class="points-toggle">
            <input 
              id="use-points"
              v-model="usePoints"
              type="checkbox"
              @change="handlePointsChange"
              :disabled="paymentStatus === 'processing'"
            >
            <label for="use-points">使用积分抵扣 (100积分 = 1元)</label>
          </div>
          <span class="available-points">可用积分: {{ availablePoints }}</span>
        </div>
        <div v-if="usePoints && pointsToUse > 0" class="points-discount">
          已使用 {{ pointsToUse }} 积分，抵扣 ¥{{ (pointsToUse / 100).toFixed(2) }}
        </div>
      </div>
      
      <!-- 支付方式选择 -->
      <div class="payment-methods">
        <h4>支付方式</h4>
        <div class="payment-options">
          <label class="payment-option">
            <input 
              v-model="paymentMethod"
              type="radio"
              value="wechat"
              :disabled="paymentStatus === 'processing'"
            >
            <div class="option-content">
              <div class="payment-icon">💚</div>
              <div class="payment-info">
                <div class="payment-name">微信支付</div>
                <div class="payment-desc">扫码支付，安全快捷</div>
              </div>
            </div>
          </label>
          <label class="payment-option">
            <input 
              v-model="paymentMethod"
              type="radio"
              value="alipay"
              :disabled="paymentStatus === 'processing'"
            >
            <div class="option-content">
              <div class="payment-icon">💙</div>
              <div class="payment-info">
                <div class="payment-name">支付宝</div>
                <div class="payment-desc">支付宝扫码支付</div>
              </div>
            </div>
          </label>
          <label class="payment-option">
            <input 
              v-model="paymentMethod"
              type="radio"
              value="card"
              :disabled="paymentStatus === 'processing'"
            >
            <div class="option-content">
              <div class="payment-icon">💳</div>
              <div class="payment-info">
                <div class="payment-name">会员卡充值</div>
                <div class="payment-desc">使用会员卡余额支付</div>
              </div>
            </div>
          </label>
          <label class="payment-option">
            <input 
              v-model="paymentMethod"
              type="radio"
              value="points"
              :disabled="paymentStatus === 'processing' || availablePoints < product.price * 100"
            >
            <div class="option-content">
              <div class="payment-icon">🎯</div>
              <div class="payment-info">
                <div class="payment-name">全部使用积分</div>
                <div class="payment-desc">{{ product.price * 100 }}积分</div>
              </div>
            </div>
          </label>
        </div>
      </div>
      
      <!-- 服务条款 -->
      <div class="terms-section">
        <label class="terms-option">
          <input 
            v-model="paymentForm.agreeTerms"
            type="checkbox"
            :disabled="paymentStatus === 'processing'"
          >
          <span>我已阅读并同意</span>
          <a href="/terms" target="_blank">服务条款</a>
          <span>和</span>
          <a href="/privacy" target="_blank">隐私政策</a>
        </label>
      </div>
      
      <!-- 支付按钮 -->
      <div class="payment-actions">
        <button 
          class="btn btn-outline"
          @click="closeModal"
          :disabled="paymentStatus === 'processing'"
        >
          取消
        </button>
        <button 
          class="btn btn-primary"
          @click="handlePayment"
          :disabled="paymentStatus === 'processing' || !paymentForm.agreeTerms"
        >
          <span v-if="paymentStatus === 'idle'">确认支付 ¥{{ finalPrice.toFixed(2) }}</span>
          <span v-else-if="paymentStatus === 'processing'">支付处理中...</span>
          <span v-else-if="paymentStatus === 'success'">支付成功！</span>
          <span v-else-if="paymentStatus === 'error'">支付失败</span>
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 弹窗蒙层 */
.payment-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 1rem;
}

/* 会员等级徽章样式 */
.user-level-badge {
  display: inline-block;
  padding: 2px 8px;
  background-color: #d4af37;
  color: white;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

/* 票种特点标签样式 */
.feature-tag {
  display: inline-block;
  padding: 2px 8px;
  margin: 2px;
  background-color: #f5f1e6;
  border: 1px solid #d4af37;
  border-radius: 12px;
  font-size: 12px;
  color: #666;
}

/* 弹窗容器 */
.payment-modal {
  background-color: white;
  border-radius: 12px;
  width: 100%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 5px 25px rgba(0, 0, 0, 0.2);
  position: relative;
}

/* 弹窗头部 */
.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem 2rem;
  border-bottom: 1px solid var(--color-border);
}

.modal-title {
  font-size: 1.5rem;
  font-weight: bold;
  color: var(--color-secondary);
  margin: 0;
}

.close-button {
  background: none;
  border: none;
  font-size: 2rem;
  color: var(--color-text-light);
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.3s ease;
}

.close-button:hover:not(:disabled) {
  background-color: var(--color-background-soft);
}

.close-button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

/* 状态提示 */
.alert {
  margin: 1rem 2rem;
  padding: 1rem;
  border-radius: 8px;
  font-size: 0.9rem;
  text-align: center;
}

.alert.success {
  background-color: rgba(72, 187, 120, 0.1);
  color: var(--color-success);
  border: 1px solid rgba(72, 187, 120, 0.3);
}

.alert.error {
  background-color: rgba(229, 62, 62, 0.1);
  color: var(--color-error);
  border: 1px solid rgba(229, 62, 62, 0.3);
}

/* 订单信息 */
.order-summary {
  padding: 1.5rem 2rem;
  border-bottom: 1px solid var(--color-border);
}

.order-summary h4 {
  font-size: 1.2rem;
  color: var(--color-secondary);
  margin: 0 0 1rem 0;
}

.order-details {
  display: flex;
  flex-direction: column;
  gap: 0.8rem;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-label {
  color: var(--color-text-light);
  font-size: 0.9rem;
}

.detail-value {
  font-size: 1rem;
  color: var(--color-text);
}

.original-price {
  text-decoration: line-through;
  color: var(--color-text-light);
}

.discount .detail-value {
  color: var(--color-error);
  font-weight: bold;
}

.total {
  margin-top: 0.5rem;
  padding-top: 0.8rem;
  border-top: 1px dashed var(--color-border);
}

.total .detail-label {
  font-weight: bold;
  color: var(--color-text);
}

.total-price {
  font-size: 1.3rem;
  font-weight: bold;
  color: var(--color-error);
}

/* 用户信息表单 */
.user-info-form {
  padding: 1.5rem 2rem;
  border-bottom: 1px solid var(--color-border);
}

.user-info-form h4 {
  font-size: 1.2rem;
  color: var(--color-secondary);
  margin: 0 0 1rem 0;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.form-group label {
  font-size: 0.9rem;
  color: var(--color-text);
  font-weight: bold;
}

.form-group input {
  padding: 0.8rem;
  border: 1px solid var(--color-border);
  border-radius: 6px;
  font-size: 1rem;
  transition: border-color 0.3s ease;
}

.form-group input:focus {
  outline: none;
  border-color: var(--color-primary);
  box-shadow: 0 0 0 2px rgba(3, 102, 214, 0.1);
}

.form-group input:disabled {
  background-color: var(--color-background-soft);
  cursor: not-allowed;
}

/* 优惠券 */
.coupon-section {
  padding: 1.5rem 2rem;
  border-bottom: 1px solid var(--color-border);
}

.coupon-toggle {
  display: flex;
  align-items: center;
  gap: 0.8rem;
}

.coupon-toggle input[type="checkbox"] {
  width: 18px;
  height: 18px;
  accent-color: var(--color-primary);
}

.coupon-toggle label {
  font-size: 1rem;
  color: var(--color-text);
  cursor: pointer;
}

.coupon-input-group {
  margin-top: 1rem;
  display: flex;
  align-items: center;
  gap: 0.8rem;
}

.coupon-input-group input {
  flex: 1;
  padding: 0.8rem;
  border: 1px solid var(--color-border);
  border-radius: 6px;
  font-size: 1rem;
}

.coupon-input-group button {
  padding: 0.8rem 1.5rem;
}

.coupon-valid {
  color: var(--color-success);
  font-weight: bold;
  font-size: 0.9rem;
}

/* 积分抵扣 */
.points-section {
  padding: 1.5rem 2rem;
  border-bottom: 1px solid var(--color-border);
}

.points-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.8rem;
}

.points-toggle {
  display: flex;
  align-items: center;
  gap: 0.8rem;
}

.points-toggle input[type="checkbox"] {
  width: 18px;
  height: 18px;
  accent-color: var(--color-primary);
}

.points-toggle label {
  font-size: 1rem;
  color: var(--color-text);
  cursor: pointer;
}

.available-points {
  font-size: 0.9rem;
  color: var(--color-text-light);
}

.points-discount {
  background-color: rgba(72, 187, 120, 0.1);
  color: var(--color-success);
  padding: 0.6rem 1rem;
  border-radius: 6px;
  font-size: 0.9rem;
  font-weight: bold;
}

/* 支付方式 */
.payment-methods {
  padding: 1.5rem 2rem;
  border-bottom: 1px solid var(--color-border);
}

.payment-methods h4 {
  font-size: 1.2rem;
  color: var(--color-secondary);
  margin: 0 0 1rem 0;
}

.payment-options {
  display: flex;
  flex-direction: column;
  gap: 0.8rem;
}

.payment-option {
  position: relative;
  cursor: pointer;
  padding: 1rem;
  border: 1px solid var(--color-border);
  border-radius: 8px;
  transition: all 0.3s ease;
}

.payment-option:hover:not(:disabled) {
  border-color: var(--color-primary);
  background-color: rgba(3, 102, 214, 0.05);
}

.payment-option:has(input:checked) {
  border-color: var(--color-primary);
  background-color: rgba(3, 102, 214, 0.1);
}

.payment-option:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.payment-option input[type="radio"] {
  position: absolute;
  opacity: 0;
}

.option-content {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.payment-icon {
  font-size: 1.8rem;
}

.payment-info {
  display: flex;
  flex-direction: column;
  gap: 0.2rem;
}

.payment-name {
  font-weight: bold;
  color: var(--color-text);
}

.payment-desc {
  font-size: 0.8rem;
  color: var(--color-text-light);
}

/* 服务条款 */
.terms-section {
  padding: 1.5rem 2rem;
  border-bottom: 1px solid var(--color-border);
}

.terms-option {
  display: flex;
  align-items: flex-start;
  gap: 0.8rem;
  font-size: 0.9rem;
  line-height: 1.5;
}

.terms-option input[type="checkbox"] {
  margin-top: 0.2rem;
  width: 18px;
  height: 18px;
  accent-color: var(--color-primary);
}

.terms-option a {
  color: var(--color-primary);
  text-decoration: none;
}

.terms-option a:hover {
  text-decoration: underline;
}

/* 操作按钮 */
.payment-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  padding: 1.5rem 2rem;
}

.payment-actions .btn {
  min-width: 120px;
  padding: 0.8rem 1.5rem;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .form-row {
    grid-template-columns: 1fr;
  }
  
  .payment-actions {
    flex-direction: column;
  }
  
  .payment-actions .btn {
    width: 100%;
  }
}
</style>